package com.gexiaobao.pigeon.ui.fragment.mall.store

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.fragment.app.setFragmentResult
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.StoreInfoResponse
import com.gexiaobao.pigeon.app.model.param.CreateShopParam
import com.gexiaobao.pigeon.app.model.param.EditShopInfoParam
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.MeSandboxFileEngine
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.FragmentOpenStoreBinding
import com.gexiaobao.pigeon.viewmodel.MerchantStoresViewModel
import com.lljjcoder.Interface.OnCityItemClickListener
import com.lljjcoder.bean.CityBean
import com.lljjcoder.bean.DistrictBean
import com.lljjcoder.bean.ProvinceBean
import com.lljjcoder.citywheel.CityConfig
import com.lljjcoder.style.citypickerview.CityPickerView
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.zs.easy.imgcompress.EasyImgCompress
import com.zs.easy.imgcompress.listener.OnCompressSinglePicListener
import com.zs.easy.imgcompress.util.GBMBKBUtil
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import java.io.File

/**
 * @Author      : hxw
 * @Date        : 2023/7/4 8:26
 * @Describe    : 开通店铺
 */
class FragmentOpenStore : BaseFragment<MerchantStoresViewModel, FragmentOpenStoreBinding>() {

    private var type: String? = ""
    private var shopId = 0
    private val mPicker = CityPickerView()
    private lateinit var storeInfoResponse: StoreInfoResponse
    private var shopServiceIds = ""
    private var checkedCertifiedContent = ""
    private var checkedAfterSalesContent = ""
    private var checkedSendContent = ""
    private var mImageId = 0

    companion object {
        const val intentType: String = "intentType"
        const val data: String = "data"
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.tvOrderState.text = getString(R.string.open_store)
        checkedCertifiedContent = getString(R.string.genuine_guarantee)
        checkedAfterSalesContent = getString(R.string.Provide_after_sale)
        checkedSendContent = getString(R.string.goods_72_hours_send)
        type = arguments?.getString(intentType)
        if (type == "2") {
            try {
                storeInfoResponse = arguments?.getParcelable(data)!!
                if (::storeInfoResponse.isInitialized) {
                    mDatabind.data = storeInfoResponse
                    shopId = storeInfoResponse.id
                    ImageLoaderManager.loadCircleImage(context, storeInfoResponse.shopPicUrl, mDatabind.ivShopLogo)
                }
                mDatabind.tvSubmitStoreInfo.text = getString(R.string.save)
            } catch (e: Exception) {
                RxToast.showToast(getString(R.string.data_acquisition_failure_and_retry))
            }
        }
        initCityData()

        val isCheckedCertified = KvUtils.decodeBooleanTure("isCheckedCertified", true)
        val isCheckedAfterSales = KvUtils.decodeBooleanTure("isCheckedAfterSales", true)
        val isCheckedSend = KvUtils.decodeBooleanTure("isCheckedSend", true)
        mDatabind.switchCertifiedProducts.isChecked = isCheckedCertified
        mDatabind.switchProvideAfterSales.isChecked = isCheckedAfterSales
        mDatabind.switchSevenTyTwoSend.isChecked = isCheckedSend
        checkedCertifiedContent = if (isCheckedCertified) getString(R.string.genuine_guarantee) + "," else ""
        checkedAfterSalesContent = if (isCheckedAfterSales) getString(R.string.Provide_after_sale) + "," else ""
        checkedSendContent = if (isCheckedSend) getString(R.string.goods_72_hours_send) else ""

        mDatabind.switchCertifiedProducts.setOnCheckedChangeListener { _, isChecked ->
            KvUtils.encode("isCheckedCertified", isChecked)
            checkedCertifiedContent = if (isChecked)
                getString(R.string.genuine_guarantee) + "," else ""
        }
        mDatabind.switchProvideAfterSales.setOnCheckedChangeListener { _, isChecked ->
            KvUtils.encode("isCheckedAfterSales", isChecked)
            checkedAfterSalesContent = if (isChecked)
                getString(R.string.Provide_after_sale) + "," else ""

        }
        mDatabind.switchSevenTyTwoSend.setOnCheckedChangeListener { _, isChecked ->
            KvUtils.encode("isCheckedSend", isChecked)
            checkedSendContent = if (isChecked)
                getString(R.string.goods_72_hours_send) else ""
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.evaluateImageResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it != null) {
                ImageLoaderManager.loadCircleImageFall(context, it.address, mDatabind.ivShopLogo, R.mipmap.icon_upload_shop_logo)
                mImageId = it.id
            }
        }
        /** 编辑店铺 */
        mViewModel.editStoreResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                setFragmentResult("isOpen", Bundle().apply {
                    putInt("isOpen", 1)
                })
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 创建店铺 */
        mViewModel.createStoreResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                RxToast.showToast(getString(R.string.store_opened))
                setFragmentResult("isOpen", Bundle().apply {
                    putInt("isOpen", 1)
                })
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.ivBack, mDatabind.tvSubmitStoreInfo, mDatabind.llStoreAddress, mDatabind.llShopLogo) {
            when (it) {
                mDatabind.llShopLogo -> {
                    upLoadShopLogo()
                }

                mDatabind.ivBack -> {
                    nav().navigateUp()
                }

                mDatabind.tvSubmitStoreInfo -> {
                    createStore()
                }

                mDatabind.llStoreAddress -> {
                    hideSoftKeyboard(activity)
                    mPicker.showCityPicker()
                }
            }
        }
    }

    private fun upLoadShopLogo() {
        val selectionModel: PictureSelectionModel = PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCropEngine(PictureUtil.getCropFileEngine())
            .setCompressEngine(PictureUtil.getCompressFileEngine())
            .setSandboxFileEngine(MeSandboxFileEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setCameraInterceptListener(PictureUtil.getCustomCameraEvent())
            .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
            .setPreviewInterceptListener(PictureUtil.getPreviewInterceptListener())
            .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
            .setQueryFilterListener { false }
            .isLoopAutoVideoPlay(false)
            .isPageSyncAlbumCount(true)
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)
            .isOpenClickSound(true)
            .isPreviewImage(true)
            .isMaxSelectEnabledMask(true)
            .isDirectReturnSingle(true)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: ArrayList<LocalMedia>?) {
                /** 方案2：压缩图片后上传 */
//                val mRealPath = result!![0].realPath
//                val bitmap = BitmapFactory.decodeFile(mRealPath)
//                val bitmapCompress = ImgUtils.compressByQuality(bitmap, 500)
//                val fileCompress = ImgUtils.saveBitmapFile(bitmapCompress)
//                showLoading(getString(R.string.loading))
//                mViewModel.uploadFile(fileCompress)
                if (!result.isNullOrEmpty()) {
                    // 把单张图片压缩到1024k以内 同时像素不超过1200（宽、高都不大于1200）
                    EasyImgCompress.withSinglePic(context, result[0].realPath)
                        .maxPx(1200)
                        .maxSize(1024)
                        .enableLog(true)
                        .setOnCompressSinglePicListener(object : OnCompressSinglePicListener {
                            override fun onStart() {
                                LogUtils.debugInfo("onStart")
                            }

                            override fun onSuccess(file: File) {
                                showLoading(getString(R.string.loading))
                                mViewModel.uploadFile(file)
                                LogUtils.debugInfo("onSuccess size = " + GBMBKBUtil.getSize(file.length()) + " getAbsolutePath= " + file.absolutePath)
                            }

                            override fun onError(error: String) {
                                LogUtils.debugInfo("onError error = $error")
                            }
                        }).start()
                }
            }

            override fun onCancel() {}
        })
    }

    private fun createStore() {
        val shopName = mDatabind.etStoreName.text.toString().trim()
        val shopPhone = mDatabind.etStoreContactsPhone.text.toString().trim()
        val shopContactsName = mDatabind.etStoreContactsName.text.toString().trim()
        val shopAddress = mDatabind.tvStoreAddress.text.toString().trim()
        when {
            shopName.isEmpty() -> showMessage("未输入商铺名称")
            shopPhone.isEmpty() -> showMessage("未输入商铺联系电话")
            shopContactsName.isEmpty() -> showMessage("未输入商铺联系人姓名")
            shopContactsName.isEmpty() -> showMessage("选择店铺地址")
            else -> {
                shopServiceIds = checkedCertifiedContent + checkedAfterSalesContent + checkedSendContent
                when (type) {
                    "1" -> {
                        val param = CreateShopParam(
                            shopName = shopName,
                            contactPerson = shopContactsName,
                            contactPhone = shopPhone,
                            address = shopAddress,
                            addressDetail = mDatabind.etStoreDetailAddress.text.toString().trim(),
                            shopServiceIds = shopServiceIds,
                            shopPicId = mImageId
                        )
                        showLoading(getString(R.string.loading))
                        mViewModel.createShop(param)
                    }

                    "2" -> {
                        val param = EditShopInfoParam(
                            shopId = shopId,
                            shopName = shopName,
                            contactPerson = shopContactsName,
                            contactPhone = shopPhone,
                            address = shopAddress,
                            addressDetail = mDatabind.etStoreDetailAddress.text.toString().trim(),
                            shopServiceIds = shopServiceIds,
                            shopPicId = mImageId
                        )
                        showLoading(getString(R.string.loading))
                        mViewModel.editAppShop(param)
                    }
                }

            }
        }
    }

    private fun initCityData() {
        val cityConfig = CityConfig.Builder().build()
        cityConfig.title = getString(R.string.elect_the_area)
        cityConfig.titleTextSize = 20
        cityConfig.confirmTextSize = 18
        cityConfig.cancelTextSize = 18
        cityConfig.titleTextSize = 18
        cityConfig.visibleItems = 8
        cityConfig.defaultProvinceName = getString(R.string.shandong_province)//默认显示的省份
        cityConfig.defaultCityName = getString(R.string.qingdao_city)
        cityConfig.customItemLayout = R.layout.item_city
        cityConfig.customItemTextViewId = R.id.item_city_name_tv
        mPicker.init(context)
        mPicker.setConfig(cityConfig)

        mPicker.setOnCityItemClickListener(object : OnCityItemClickListener() {
            @SuppressLint("SetTextI18n")
            override fun onSelected(
                province: ProvinceBean?,
                city: CityBean?,
                district: DistrictBean?
            ) {
                super.onSelected(province, city, district)
                mDatabind.tvStoreAddress.text = province.toString() + " - " + city + " - " + district
            }
        })
    }
}